<template>
  <div class="page">
    <div class="message-list">
      <div v-for="item in messageList" 
           :key="item.id" 
           class="message-item"
           :class="[
             {'unread': item.readStatus === '0'},
             `type-${getMessageClass(item.messageType)}`
           ]"
           @click="showMessageDetail(item)">
        <div class="message-icon">
          <img :src="item.readStatus === '0' ? require('@/assets/img/unread.png') : require('@/assets/img/read.png')" 
               alt="" 
               class="status-icon"/>
        </div>
        <div class="message-content">
          <div class="message-header">
            <span class="message-type" :class="`type-${getMessageClass(item.messageType)}`">
              {{ item.messageType }}
            </span>
            <span class="message-time">{{ formatTime(item.notificationTime) }}</span>
          </div>
          <div class="message-title">{{ item.title }}</div>
        </div>
        <i class="el-icon-arrow-right"></i>
      </div>
      
      <!-- 空状态 -->
      <div v-if="messageList.length === 0" class="empty-state">
        暂无消息
      </div>
    </div>

    <!-- 消息详情弹框 -->
    <el-dialog
      title="消息详情"
      :visible.sync="dialogVisible"
      width="90%"
      custom-class="message-dialog"
    >
      <div class="message-detail" v-if="currentMessage">
        <h3 class="detail-title">{{ currentMessage.title }}</h3>
        <div class="detail-info">
          <span class="detail-type" :class="`type-${getMessageClass(currentMessage.messageType)}`">
            {{ currentMessage.messageType }}
          </span>
          <span class="detail-time">{{ formatTime(currentMessage.notificationTime) }}</span>
        </div>
        <div class="detail-content">{{ currentMessage.content }}</div>
        
        <div class="detail-notes" v-if="showNotes">
          <div class="notes-title">您已回复：</div>
          <div class="notes-content">{{ currentMessage.notes }}</div>
        </div>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">关 闭</el-button>
        <el-button 
          type="primary" 
          @click="showReplyDialog"
          v-if="currentMessage && currentMessage.messageType === '私信'"
        >
          回复私信
        </el-button>
        <el-button 
          type="primary" 
          @click="goToDetail"
          v-if="currentMessage && (currentMessage.messageType === '活动' || currentMessage.messageType === '合作')"
        >
          查看详情
        </el-button>
      </span>
    </el-dialog>

    <!-- 添加回复弹框 -->
    <el-dialog
      title="回复私信"
      :visible.sync="replyDialogVisible"
      width="90%"
      custom-class="reply-dialog"
      append-to-body
    >
      <el-form :model="replyForm" ref="replyForm" :rules="replyRules">
        <el-form-item prop="content">
          <el-input
            type="textarea"
            v-model="replyForm.content"
            :rows="4"
            placeholder="请输入回复内容..."
            :maxlength="200"
            show-word-limit
          ></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="replyDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="handleReply" :loading="replying">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { getMessageList, getMessageDetail, replyPrivateMessage } from "@/api/api";

export default {
  data() {
    return {
      messageList: [],
      pageNum: 1,
      pageSize: 10,
      dialogVisible: false,
      currentMessage: null,
      replyDialogVisible: false,
      replying: false,
      replyForm: {
        content: ''
      },
      replyRules: {
        content: [
          { required: true, message: '请输入回复内容', trigger: 'blur' },
          { min: 1, max: 200, message: '长度在 1 到 200 个字符', trigger: 'blur' }
        ]
      }
    };
  },
  
  created() {
    this.loadMessageList();
  },
  
  computed: {
    // 判断是否为私信类型消息
    isPrivateMessage() {
      return this.currentMessage && 
        (this.currentMessage.messageType === '私信' || 
         this.currentMessage.messageType === '私信回复');
    },
    
    // 判断是否显示 notes
    showNotes() {
      return this.currentMessage && 
             this.currentMessage.notes && 
             ['私信', '私信回复'].includes(this.currentMessage.messageType);
    }
  },
  
  methods: {
    async loadMessageList() {
      try {
        const res = await getMessageList({
          pageNum: this.pageNum.toString(),
          pageSize: this.pageSize.toString()
        });
        
        if (res.code === 200) {
          this.messageList = res.data || [];
        }
      } catch (error) {
        console.error('获取消息列表失败:', error);
      }
    },
    
    formatTime(time) {
      if (!time) return '';
      const date = new Date(time);
      const now = new Date();
      
      // 如果是今天的消息，只显示时间
      if (date.toDateString() === now.toDateString()) {
        return date.toLocaleTimeString('zh-CN', { 
          hour: '2-digit', 
          minute: '2-digit' 
        });
      }
      
      // 否则显示完整日期
      return date.toLocaleDateString('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit'
      });
    },
    
    async showMessageDetail(item) {
      try {
        const res = await getMessageDetail({
          id: item.id
        });
        
        if (res.code === 200 && res.data) {
          this.currentMessage = res.data;
          this.dialogVisible = true;
          
          // 如果消息是未读状态，查看后需要刷新列表
          if (item.readStatus === '0') {
            this.loadMessageList();
          }
        }
      } catch (error) {
        console.error('获取消息详情失败:', error);
      }
    },
    
    handleDetailConfirm() {
      this.dialogVisible = false;
      this.currentMessage = null;
    },
    
    goToDetail() {
      if (!this.currentMessage) return;
      
      const { messageType, correspondingId } = this.currentMessage;
      let path = '';
      
      if (messageType === '活动') {
        path = '/activity/details';
      } else if (messageType === '合作') {
        path = '/mutual/details';
      }
      
      if (path) {
        this.dialogVisible = false;
        this.$router.push({
          path,
          query: { 
            id: correspondingId
          }
        });
      }
    },
    
    getMessageClass(type) {
      const typeMap = {
        '活动': 'activity',
        '合作': 'mutual',
        '系统': 'system',
        '私信': 'private',
        '私信回复': 'private'
      };
      return typeMap[type] || 'default';
    },

    // 显示回复弹框
    showReplyDialog() {
      this.replyDialogVisible = true;
      this.replyForm.content = '';
    },

    // 处理回复提交
    async handleReply() {
      try {
        await this.$refs.replyForm.validate();
        
        this.replying = true;
        const res = await replyPrivateMessage({
          id: this.currentMessage.id,
          content: this.replyForm.content
        });

        if (res.code === 200) {
          this.$message.success('回复成功');
          // 关闭回复弹框
          this.replyDialogVisible = false;
          // 关闭详情弹框
          this.dialogVisible = false;
          // 重置当前消息
          this.currentMessage = null;
          // 刷新消息列表
          this.loadMessageList();
        } else {
          this.$message.error(res.message || '回复失败');
        }
      } catch (error) {
        console.error('回复私信失败:', error);
        this.$message.error('回复失败，请重试');
      } finally {
        this.replying = false;
      }
    }
  }
};
</script>

<style lang="less" scoped>
.message-list {
  padding: 10px 0;
  background: #fff;
}

.message-item {
  display: flex;
  align-items: center;
  padding: 15px;
  border-bottom: 1px solid #eee;
  background: #fff;
  cursor: pointer;
  
  &.unread {
    background: #f5f7fa;
    
    .message-title {
      font-weight: bold;
    }
  }
  
  &:active {
    background: #f5f7fa;
  }

  // 不同类型消息的样式
  &.type-activity {
    .message-type {
      color: #409EFF;
      background: rgba(64, 158, 255, 0.1);
      border: 1px solid rgba(64, 158, 255, 0.2);
    }
    &.unread {
      border-left: 3px solid #409EFF;
    }
  }
  
  &.type-mutual {
    .message-type {
      color: #67C23A;
      background: rgba(103, 194, 58, 0.1);
      border: 1px solid rgba(103, 194, 58, 0.2);
    }
    &.unread {
      border-left: 3px solid #67C23A;
    }
  }
  
  &.type-system {
    .message-type {
      color: #E6A23C;
      background: rgba(230, 162, 60, 0.1);
      border: 1px solid rgba(230, 162, 60, 0.2);
    }
    &.unread {
      border-left: 3px solid #E6A23C;
    }
  }
  
  &.type-default {
    .message-type {
      color: #909399;
      background: rgba(144, 147, 153, 0.1);
      border: 1px solid rgba(144, 147, 153, 0.2);
    }
    &.unread {
      border-left: 3px solid #909399;
    }
  }

  // 添加私信类型的样式
  &.type-private {
    .message-type {
      color: #FF69B4;  // 使用粉色表示私信
      background: rgba(255, 105, 180, 0.1);
      border: 1px solid rgba(255, 105, 180, 0.2);
    }
    &.unread {
      border-left: 3px solid #FF69B4;
    }
  }
}

.message-icon {
  margin-right: 12px;
  
  .status-icon {
    width: 20px;
    height: 20px;
    object-fit: contain;
  }
}

.message-content {
  flex: 1;
  margin-right: 10px;
}

.message-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 8px;
}

.message-type {
  display: inline-block;
  padding: 2px 8px;
  border-radius: 12px;
  font-size: 12px;
  line-height: 1.4;
}

.message-time {
  color: #999;
  font-size: 12px;
}

.message-title {
  color: #333;
  font-size: 14px;
  line-height: 1.4;
}

.el-icon-arrow-right {
  color: #999;
  font-size: 16px;
}

.empty-state {
  text-align: center;
  padding: 30px 0;
  color: #999;
  font-size: 14px;
}

.message-dialog {
  border-radius: 8px;
  
  /deep/ .el-dialog__header {
    padding: 15px;
    border-bottom: 1px solid #eee;
    
    .el-dialog__title {
      font-size: 16px;
      font-weight: bold;
    }
  }
  
  /deep/ .el-dialog__body {
    padding: 20px;
  }
}

.message-detail {
  .detail-title {
    font-size: 16px;
    font-weight: bold;
    color: #333;
    margin: 0 0 15px 0;
  }
  
  .detail-info {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
    
    .detail-type {
      display: inline-block;
      padding: 2px 8px;
      border-radius: 12px;
      font-size: 12px;
      line-height: 1.4;
      
      &.type-activity {
        color: #409EFF;
        background: rgba(64, 158, 255, 0.1);
        border: 1px solid rgba(64, 158, 255, 0.2);
      }
      
      &.type-mutual {
        color: #67C23A;
        background: rgba(103, 194, 58, 0.1);
        border: 1px solid rgba(103, 194, 58, 0.2);
      }
      
      &.type-system {
        color: #E6A23C;
        background: rgba(230, 162, 60, 0.1);
        border: 1px solid rgba(230, 162, 60, 0.2);
      }
      
      &.type-default {
        color: #909399;
        background: rgba(144, 147, 153, 0.1);
        border: 1px solid rgba(144, 147, 153, 0.2);
      }

      &.type-private {
        color: #FF69B4;
        background: rgba(255, 105, 180, 0.1);
        border: 1px solid rgba(255, 105, 180, 0.2);
      }
    }
    
    .detail-time {
      color: #999;
      font-size: 12px;
    }
  }
  
  .detail-content {
    font-size: 14px;
    line-height: 1.6;
    color: #666;
    white-space: pre-wrap;
    word-break: break-all;
  }
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
  
  .el-button {
    margin-left: 0;  /* 覆盖 element-ui 的默认间距 */
  }
}

// 添加 notes 相关样式
.detail-notes {
  margin-top: 20px;
  padding-top: 15px;
  border-top: 1px dashed #eee;
  
  .notes-title {
    font-size: 14px;
    color: #666;
    margin-bottom: 8px;
    font-weight: 500;
  }
  
  .notes-content {
    font-size: 14px;
    line-height: 1.6;
    color: #666;
    white-space: pre-wrap;
    word-break: break-all;
    padding: 10px;
    background: #f7f9fc;
    border-radius: 4px;
  }
}

.reply-dialog {
  /deep/ .el-dialog__body {
    padding: 20px;
  }
  
  /deep/ .el-textarea__inner {
    background: #f7fafd;
    border: none;
    border-radius: 8px;
    padding: 15px;
    font-size: 14px;
    
    &::placeholder {
      color: #999;
    }
  }
}

@media screen and (max-width: 768px) {
  .reply-dialog {
    /deep/ .el-dialog {
      width: 90% !important;
      margin-top: 20vh !important;
    }
  }
}
</style>
